package com.nx.common.tools;

import cn.hutool.core.util.NumberUtil;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class StringTools {

    /**
     * 截取字符串的后length位
     *
     * @param str    目标字符串
     * @param length 位数
     * @return 子串
     */
    public static String cutLastStr(String str, int length) {
        if (length < 0) length = 0;
        if (length > str.length()) {
            return str;
        }
        return str.substring(str.length() - length);
    }

    /**
     * 填充0
     *
     * @param str
     * @param targetNum
     * @return
     */
    public static String zeroFill(String str, int targetNum) {
        if (str.length() < targetNum) {
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < targetNum - str.length(); i++) {
                stringBuilder.append("0");
            }
            return stringBuilder.append(str).toString();
        }
        return str;
    }

    /**
     * 去空格
     */
    public static String trim(String str) {
        return (str == null ? "" : str.trim());
    }

    /**
     * 是否包含字符串
     *
     * @param str  验证字符串
     * @param strs 字符串组
     * @return 包含返回true
     */
    public static boolean inStringIgnoreCase(String str, String... strs) {
        if (str != null && strs != null) {
            for (String s : strs) {
                if (str.equalsIgnoreCase(trim(s))) {
                    return true;
                }
            }
        }
        return false;
    }

    public static boolean equal(String str1, String str2) {
        if (str1 == null || str2 == null)
            return false;
        if (str1 == str2)
            return true;
        return str1.equals(str2);
    }

    public static String add(String str1, String str2, String simbol) {
        String[] strArray = str1.split(simbol);

        List<String> resultList = new ArrayList<>();
        boolean found = false;
        for (String str : strArray) {
            if (str.trim().equals(str2.trim())) {
                found = true;
            }
            resultList.add(str);
        }
        if (!found) {
            resultList.add(str2);
        }
        return String.join(",", resultList);
    }

    public static String delete(String str1, String str2, String simbol) {
        String[] strArray = str1.split(simbol);

        List<String> resultList = new ArrayList<>();
        for (String str : strArray) {
            if (!str.trim().equals(str2.trim())) {
                resultList.add(str);
            }
        }
        return String.join(",", resultList);
    }

    public static String removeSpecialChar(String str) {
        String s = "";
        if (str != null) {
            // 定义含特殊字符的正则表达式
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            s = m.replaceAll("");
        }
        return s;
    }

    public static Integer StringNumberCompare(String number1, String number2) {
        BigDecimal decimalNumber1 = new BigDecimal(number1);
        BigDecimal decimalNumber2 = new BigDecimal(number2);

        return NumberUtil.compare(decimalNumber1.doubleValue(), decimalNumber2.doubleValue());
    }

    public static Integer getNullLength(String str) {
        if (str == null) {
            return 0;
        }
        return str.length();
    }

    public static Boolean checkStrLen(String str, Integer minLength, Integer maxLength) {
        int length = 0;
        if (str != null) {
            length = str.length();
        }
        if (minLength != null) {
            if (length < minLength) {
                return false;
            }
        }
        if (maxLength != null) {
            if (length > maxLength) {
                return false;
            }
        }
        return true;
    }

    public static boolean checkEmail(String email) {
        if (CheckTools.isNullOrEmpty(email)) {
            return false;
        }
//        return email.matches("\\w+@\\w+\\.\\w+");
        return email.matches("^[A-Za-z0-9]+([_.][A-Za-z0-9]+)*@([A-Za-z0-9\\-]+\\.)+[A-Za-z]{2,6}$");
    }

    public static boolean checkNumber(String num, Integer decimalPlace) {
        if (CheckTools.isNullOrEmpty(num)) {
            return false;
        }

        if (!num.matches("([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])")) {
            return false;
        }

        if (CheckTools.isNullOrEmpty(decimalPlace)) {
            if (!num.matches("(\\d*\\.?\\d{1,2})")) {
                return false;
            }
        }
        return true;
    }

    public static boolean checkNumber(String desc, String num, Integer decimalPlace, String min, String max) {

        if (CheckTools.isNullOrEmpty(num)) {
            throw new IllegalArgumentException(String.format("%s不能为空", desc));
        }

        // 数字校验
        if (!num.matches("([0-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])")) {
            throw new IllegalArgumentException(String.format("%s不是数字", desc));
        }
        // 小数位校验
        if (CheckTools.isNotNullOrEmpty(decimalPlace)) {
            String Regular = String.format("((\\d+)(.\\d{0,%d})?)", decimalPlace);
            if (!num.matches(Regular)) {
                throw new IllegalArgumentException(String.format("%s仅允许%d位小数", desc, decimalPlace));
            }
        }
        // 范围校验-min~max
        if (min != null) {
            if (NumberUtil.compare(Double.valueOf(num), Double.valueOf(min)) < 0) {
                throw new IllegalArgumentException(String.format("%s不能小于%s", desc, min));
            }
        }
        if (max != null) {
            if (NumberUtil.compare(Double.valueOf(num), Double.valueOf(max)) > 0) {
                throw new IllegalArgumentException(String.format("%s不能大于%s", desc, max));
            }
        }
        return true;
    }

    public static Boolean isIn(String strs, String separator, String str) {
        if (CheckTools.isNullOrEmpty(strs) && CheckTools.isNullOrEmpty(str)) {
            return true;
        }
        if (CheckTools.isNullOrEmpty(strs) || CheckTools.isNullOrEmpty(str)) {
            return false;
        }
        String[] strList = strs.split(separator);
        for (String item : strList) {
            if (item.equals(str)) {
                return true;
            }
        }
        return false;
    }

    // 纯数字
    private static String DIGIT_REGEX = "[0-9]+";
    // 含有数字
    private static String CONTAIN_DIGIT_REGEX = ".*[0-9].*";
    // 纯字母
    private static String LETTER_REGEX = "[a-zA-Z]+";
    // 包含字母
    private static String CONTAIN_LETTER_REGEX = ".*[a-zA-z].*";
    // 纯中文
    private static String CHINESE_REGEX = "[\u4e00-\u9fa5]";
    // 仅仅包含字母和数字
    private static String LETTER_DIGIT_REGEX = "^[a-z0-9A-Z]+$";
    private static String CHINESE_LETTER_REGEX = "([\u4e00-\u9fa5]+|[a-zA-Z]+)";
    private static String CHINESE_LETTER_DIGIT_REGEX = "^[a-z0-9A-Z\u4e00-\u9fa5]+$";


    /**
     * 判断字符串是否仅含有数字和字母
     *
     * @param str
     * @return
     */
    public static boolean judgeContainDigit(String str) {
        return str.matches(CONTAIN_DIGIT_REGEX);
    }

    // public static void main(String[] args) {
    //     String workNum = "03060001";
    //     String lastNum = workNum.substring(4);
    //     System.out.println("看看lastNum：" + lastNum);
    //     BigDecimal add = NumberUtil.add(lastNum, "1");
    //     System.out.println("看看add：" + add);
    //     String target = zeroFill("" + add, 4);
    //     System.out.println("看看target：" + target);
    // }



    /**
     * 处理特殊字符问题
     *
     * @param phone
     * @return
     */
    public static String dealBlankString(String phone) {
        if (CheckTools.isNotNullOrEmpty(phone)) {
            phone = removeNonAscii(phone);
            phone = removeSomeControlChar(phone);
            phone = removeFullControlChar(phone).trim();
            return phone;
        }
        return null;
    }
    /**
     * 去除非ascii码字符
     *
     * @param str
     * @return
     */
    public static String removeNonAscii(String str) {
        return str.replaceAll("[^\\x00-\\x7F]", "");
    }
    /**
     * 去除不可打印字符
     *
     * @param str
     * @return
     */
    public static String removeNonPrintable(String str) {
        return str.replaceAll("[\\p{C}]", "");
    }

    /**
     * 去除一些控制字符 Control Char
     *
     * @param str
     * @return
     */
    public static String removeSomeControlChar(String str) {
        return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", ""); // Some Control Char
    }

    /**
     * 去除一些换行制表符
     *
     * @param str
     * @return
     */
    public static String removeFullControlChar(String str) {
        return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
    }


    public static String addToList(String listStr, String addStr) {
        if (CheckTools.isNullOrEmpty(listStr)) {
            return addStr;
        }

        Set<String> set = Arrays.stream(listStr.split(",")).collect(Collectors.toSet());
        set.add(addStr);

        return String.join(",", set);
    }

    public static String delFromList(String listStr, String delStr) {
        if (CheckTools.isNullOrEmpty(listStr)) {
            return listStr;
        }

        Set<String> set = Arrays.stream(listStr.split(",")).collect(Collectors.toSet());
        set.remove(delStr);

        return String.join(",", set);
    }

}
